/**
 * Description: 客户端管理
 * @author:yueyemoyan
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-05-09   yueyemoyan       1.0.0     Initial
 */
package com.metro.activation.biz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.github.pagehelper.PageInfo;
import com.metro.activation.biz.beans.vo.BizClient;
import com.metro.activation.biz.service.inf.IBizClientService;
import com.metro.activation.common.beans.constant.DicTypeEnum;
import com.metro.activation.common.beans.constant.JxlsTemplateEnum;
import com.metro.activation.common.utils.DicUtil;
import com.metro.activation.common.utils.Redeem;
import com.metro.activation.common.utils.UserUtil;
import com.metro.activation.common.utils.cache.CacheUtil;
import com.metro.activation.web.controller.BaseController;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.excel.JxlsView;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
 /**
 * 客户端管理<br>
 *
 * @author:yueyemoyan
 * @since:1.0.0
 * @version [1.0.0, 2018-05-09]
 */
@Controller
@RequestMapping("/bizClient")
public class BizClientController extends BaseController {
    //菜单编码
    private static final String menuCode = "biz_client";
    //模块描述
    private static final String MODULE_DESC = "客户端管理";
    @Autowired
    private IBizClientService bizclientService;
    @Override
    protected String getViewDir() {
        return "biz/";
    }
    
    /**
     * 去查询客户端管理
     * 
     * @param bizclient 客户端管理页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询客户端管理列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(BizClient bizclient) {
        ModelAndView mav = new ModelAndView();
        try {
        	mav.addObject("activationStatusList", DicUtil.getLabelValueList(DicTypeEnum.ACTIVATION_STATUS));
            mav.setViewName(getView("bizclient_list"));
            mav.addObject("searchEntity", bizclient);
        } catch (Exception ex) {
            log.error("查询客户端管理出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询客户端管理
     *
     * @param bizclient 客户端管理页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询客户端管理列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(BizClient bizclient, Page page, QueryParams<BizClient> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setEntity(bizclient);
            PageInfo<BizClient> pageInfo = bizclientService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询客户端管理出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增客户端管理
     * 
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增客户端管理")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            initCreateOrUpdateFrom(mav, "create");
        } catch (Exception ex) {
            log.error("去新增客户端管理出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    /**
     * 初始化新增修改客户端管理所需参数
     * @author yueyemoyan
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action){
        mav.addObject("action", action);
        mav.setViewName(getView("bizclient_form"));
    }
    
    /**
     * 新增客户端管理
     * 
     * @param entity 客户端管理页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增客户端管理")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveBizClient(BizClient entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = bizclientService.save(entity);
            jr.setResult(res);
            log.debug("新增客户端管理成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增客户端管理出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 删除客户端管理
     * 
     * @param id 客户端管理页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除客户端管理")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete/{id}", method = { RequestMethod.DELETE })
    @ResponseBody
    public JsonResult delete(@PathVariable String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除客户端管理id={}",id);
            IResult codeMsg = bizclientService.deleteByIds(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除客户端管理出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去修改客户端管理
     * 
     * @param id 客户端管理页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改客户端管理")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            BizClient entity = bizclientService.getById(id);
            mav.addObject("entity", entity);
            initCreateOrUpdateFrom(mav,"edit");
        } catch (Exception ex) {
            log.error("去修改客户端管理", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

    /**
     * 修改客户端管理
     * 
     * @param entity 客户端管理页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改客户端管理")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateBizClient(BizClient entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = bizclientService.update(entity);
            jr.setResult(res);
            log.debug("修改客户端管理成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改客户端管理出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去查看客户端管理
     * 
     * @param id 客户端管理页面表单对象唯一标识
     * @return 结果视图
     * @author yueyemoyan
     * @since [1.0.0]
     * @version [1.0.0, 2018-05-09]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看客户端管理详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("entity", bizclientService.getById(id));
            mav.setViewName(getView("bizclient_info"));
        } catch (Exception ex) {
            log.error("查看客户端管理出错", ex);
        }
        return mav;
        
    }
    
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "校验激活码")
    @RequestMapping(value = "codes/check", method = { RequestMethod.POST })
    @ResponseBody
    public JsonResult checkCode(HttpServletRequest request, HttpServletResponse response){
    	JsonResult jr = new JsonResult();
    	String codes = request.getParameter("codes");
    	try {
            log.debug("导入激活码code={}",codes);
            String[] codeStr = codes.split("\n"); // 按换行符截取
            List<String> codeList = new ArrayList<String>();
            List<BizClient> bizClientList = new ArrayList<BizClient>(); //入库使用
            List<BizClient> allClientList = new ArrayList<BizClient>(); // 激活码校验导出使用
            //检测是否符合规则
            int errCount = 0;
            int exitCount = 0;
            int successCount = 0;
            for (int i = 0; i < codeStr.length; i++) {
            	BizClient client = new BizClient();
            	client.setActivationCode(codeStr[i]);
            	//首先判断符不符合激活码规则
            	boolean flag = Redeem.VerifyCode(codeStr[i]);
            	if(!flag){
            		client.setMsgStr("无效");
            		allClientList.add(client);
            		errCount++; //不符合规则,计数
            		continue;
            	}
            	
            	//判断是否 已经存在
            	BizClient param = new BizClient();
            	param.setActivationCode(codeStr[i]);
            	List<BizClient> getList = bizclientService.queryForList(param);
            	if(getList.size() > 0){
            		client.setMsgStr("已存在");
            		allClientList.add(client);
            		exitCount++ ;// 记录已存在数量
            		continue;
            	}
            	
            	codeList.add(codeStr[i]); //如果符合规则添加到新的list中
            	client.setMsgStr("有效");
            	allClientList.add(client);
        		client.setActivationStatus("1"); //设置激活码未激活
        		bizClientList.add(client);
        		successCount++;
			}
            
            // 将符合规则的激活码入库
            if(bizClientList.size() > 0){
//            	bizclientService.batchSave(bizClientList);
            }
            
            //将数据组织好后放入缓存中
            CacheUtil.put(UserUtil.getCurrUserId() + CacheUtil.ALL_CODE, allClientList, 3600);// 校验后的激活码
            CacheUtil.put(UserUtil.getCurrUserId() + CacheUtil.SUCCESS_CODE, bizClientList, 3600); //成功的激活码
            
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("errCount", errCount);
            result.put("exitCount", exitCount);
            result.put("successCount", successCount);
            result.put("bizClientList", bizClientList);
    		jr.setResult(ResultCode.SUCCESS);
    		jr.setData(result);
        } catch (Exception ex) {
            log.error("校验激活码出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
    	return jr;
    }
    
    /**
     * 导出激活码校验结果
     * @param request
     * @param response
     */
    @SuppressWarnings("unchecked")
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "导出激活码校验结果")
	@RequestMapping(value = "codes/export")
    public ModelAndView export(HttpServletRequest request, HttpServletResponse response){
    	// 获取缓存中的数据
    	List<BizClient> list = (List<BizClient>) CacheUtil.get(UserUtil.getCurrUserId() + CacheUtil.ALL_CODE);
        return new ModelAndView(new JxlsView(JxlsTemplateEnum.CHECK_OCDE, list));
    }
    
    /**
     * 导入激活码
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
	@BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "导入激活码")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "codes/import", method = { RequestMethod.POST })
    @ResponseBody
    public JsonResult importCode(HttpServletRequest request, HttpServletResponse response){
    	JsonResult jr = new JsonResult();
    	// 获取缓存中的数据
    	try {
    		List<BizClient> list = (List<BizClient>) CacheUtil.get(UserUtil.getCurrUserId() + CacheUtil.SUCCESS_CODE);
        	if(list.size() > 0){
        		bizclientService.batchSave(list);
        	}
        	jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex) {
            log.error("导入激活码出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
    	return jr;
    }
    
    
    
    /**
     * 注销
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "注销客户端")
    @RequestMapping(value="/cancel/{id}", method = { RequestMethod.POST })
    @RequiresPermissions(menuCode + ":cancel")
    @ResponseBody
    public JsonResult cancel(@PathVariable String id, HttpServletRequest request){
    	JsonResult jr = new JsonResult();
        try {
            log.debug("注销客户端id={}",id);
            IResult codeMsg = bizclientService.cancelByIds(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("注销客户端出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
}
